﻿using ConfExpert.Utility;
using ConfExpert.Utility.Grid;
using ConfOrder.Utility;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfOrder.Shirt
{
    public partial class Reserve : XForm
    {
        public Reserve(int OrderRefId)
        {
            InitializeComponent();
            this.OrderRefId = OrderRefId;
        }

        int OrderRefId;
        int WhoAmI;
        private void AutoRollSelection_Load(object sender, EventArgs e)
        {
            this.MainToolbar.Visible = true;
            WhoAmI = AppSession.UserInfo.UserId;

            gridView1.Init("COGetQtyFromIdle3", OrderRefId);
            source = gridView1.AddDetailGrid(gridView2, "ProductId");
            
            gridView1.SutunEkle("SelectedQty", typeof(decimal), "SUM(Child({FK}).SelectedQty)");
            gridView1.YanYanaGetirCoklu("SelectedQty", "ProjectedQty", "MissingQty", "IdleQty", "OtherQty");
            gridView2.RowStyle += gridView2_RowStyle;
            gridView1.RowStyle += gridView1_RowStyle;
            GridManager gm = GridManager.GetManager(gridView2);

            gm.GridMenu.AddMenu("Add", Sec);
            gm.GridMenu.AddMenu("Remove", Birak);
            gridView2.SutunEkle("Seç", typeof(bool), "");
            gridView2.FormatAsNumber(1, "Qty", "En");
            gridView2.AddSummary("Qty");
            gridView1.MakeReadOnly();
            gridView2.MakeReadOnly();
            gridView2.MakeColumnInvisible("Scan", "ProductId", "SelectedQty", "Seç");
            gridView2.SetCaptions("En:Width");
            gridView1.FormatAsNumber(1, "ProjectedQty", "IdleQty", "OtherQty", "MissingQty", "SelectedQty");
            gridView1.AddSummary("ProjectedQty", "IdleQty", "OtherQty", "MissingQty", "SelectedQty");
            gridView2.Columns["VendorId"].ColumnEdit = RI(Rp.Vendor);
            gridView2.OptionsView.EnableAppearanceOddRow = gridView2.OptionsView.EnableAppearanceEvenRow = false;
            gridView1.OptionsView.EnableAppearanceOddRow = gridView1.OptionsView.EnableAppearanceEvenRow = false;
            btnSave.ItemClick += btnSave_ItemClick;

            //splitContainerControl1.AutoSizeChanged += MySizeChanged;
            btnUygunTop_ItemClick(null, null);

            gridView2.RowCellStyle+=gridView2_RowCellStyle;
            gridView2.Columns["AyrimId"].ColumnEdit = RepositoryManager.riAyrim;
            gridView2.Columns["isIdle"].Visible = false;
            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();

            chkShowAll.CheckedChanged += chkShowAll_CheckedChanged;
            chkShowAll_CheckedChanged(null, null);
        }

        void gridView2_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            GridView gv = sender as GridView;
            if (e.RowHandle > -1)
            {
                switch (e.Column.FieldName)
                {
                    case "Qty":
                    case "Total":
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        return;
                }
            }
        }

        BindingSource source = new BindingSource();
        void chkShowAll_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            source.Filter = chkShowAll.Checked ? string.Empty : "isIdle =1";
            gridView2.BestFitColumns();
        }

        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            gridView2.BestFitColumns();
        }

        void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.EndEdit();
            gridView2.EndEdit();
            List<string> RollIds = new List<string>();
            foreach (DataRow dr in gridView2.DataTable().Select("Seç=1"))
                RollIds.Add(dr["RollId"].ToStringNN());

            if (RollIds.Count > 0)
            {
                ExecQuery("COUpdReserve", OrderRefId, string.Join(",", RollIds.ToArray()), WhoAmI);
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (((GridView)sender).GetRowCellValue(e.RowHandle, "SelectedQty").ToDecimalNN() > 0)
                e.Appearance.BackColor = Color.LightBlue;
        }

        void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            if (e.RowHandle > -1)
                if ((sender as DevExpress.XtraGrid.Views.Grid.GridView).GetRowCellValue(e.RowHandle, "Seç") != null)
                    if ((sender as DevExpress.XtraGrid.Views.Grid.GridView).GetRowCellValue(e.RowHandle, "Seç") != DBNull.Value)
                        if ((bool)(sender as DevExpress.XtraGrid.Views.Grid.GridView).GetRowCellValue(e.RowHandle, "Seç") == true)
                            e.Appearance.BackColor = Color.LightBlue;
                        else
                            e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);
        }

        void Sec(object sender, EventArgs e)
        {
            gridView1.CloseEditor();
            gridView2.CloseEditor();
            foreach (int handle in gridView2.GetSelectedRows())
            {
                gridView2.SetRowCellValue(handle, "Seç", true);
                int Qty = gridView2.GetRowCellValue(handle, "Qty").ToIntNN();
                gridView2.SetRowCellValue(handle, "SelectedQty", Qty);
            }
        }

        void Birak(object sender, EventArgs e)
        {
            gridView1.CloseEditor();
            gridView2.CloseEditor();
            foreach (int handle in gridView2.GetSelectedRows())
            {
                gridView2.SetRowCellValue(handle, "Seç", false);
                gridView2.SetRowCellValue(handle, "SelectedQty", null);
            }
        }


        void btnUygunTop_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.SelectAll();
            if (gridView1.GetSelectedRows().Length > 0)
            {
                foreach (int handle in gridView1.GetSelectedRows())
                {
                    DataRow dr = gridView1.GetDataRow(handle);
                    decimal RequiredQty = dr["ProjectedQty"].ToDecimalNN();
                    if (RequiredQty == 0)
                        continue;

                    int ProductId = dr["ProductId"].ToIntNN();

                    Dictionary<int, decimal> subSet = new Dictionary<int, decimal>();

                    foreach (DataRow xr in gridView2.DataTable().Select("isIdle = 1 AND ProductId = " + ProductId.ToString(), "Qty"))
                    {
                        xr["Seç"] = 0;
                        xr["SelectedQty"] = 0;
                        subSet.Add(xr["RollId"].ToIntZero(), xr["Qty"].ToDecimalNN());
                    }

                    List<int> selectedRollIds = SubsetSum.Select(RequiredQty, subSet);

                    foreach (int rollId in selectedRollIds)
                    {
                        DataRow drSelectedRoll = gridView2.DataTable().Select("RollId="+rollId.ToString())[0];
                        drSelectedRoll["SelectedQty"] = drSelectedRoll["Qty"];
                        drSelectedRoll["Seç"] = 1;
                    }
                }
                //UpdSepet();
            }
            gridView1.ClearSelection();

        }

    }
}
